package com.lhd.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lhd.component.RedisComponent;
import com.lhd.entity.dto.PasswordDto;
import com.lhd.entity.dto.RegisterDto;
import com.lhd.entity.dto.UserDto;
import com.lhd.entity.po.User;
import com.lhd.entity.query.UserQuery;
import com.lhd.entity.vo.ResponseVO;
import com.lhd.exception.BusinessException;
import com.lhd.service.UserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: liuhd
 * @Date: 2025/03/10
 * @Description: User控制器
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController extends ABaseController{

	@Resource
	private UserService userService;
	@Resource
	private RedisComponent redisComponent;
	
	@PostMapping("/register")
	public ResponseVO register(@RequestBody RegisterDto registerDto) {
		// 校验
		User userByPhone = userService.findUserByPhone(registerDto.getPhone());
		if (userByPhone != null) {
			throw new BusinessException("用户已存在");
		}

		if (!registerDto.getPassword().equals(registerDto.getRePassword())) {
			throw new BusinessException("两次密码不一致");
		}

		User user = new User();
		user.setUsername(registerDto.getUsername());
		user.setRole(registerDto.getRole());
		user.setPhone(registerDto.getPhone());
		user.setJobCode(registerDto.getJobCode());
		user.setEmail(registerDto.getEmail());
		user.setPassword(registerDto.getPassword());

		Long signal = userService.add(user);
		if (signal == 0) {
			throw new BusinessException("注册失败");
		}

		return getSuccessResponseVO(null);
	}

	@PostMapping("/login")
	public ResponseVO login(@RequestBody RegisterDto registerDto, HttpServletResponse response) {

		User user = userService.findUserByPhone(registerDto.getPhone());
		if (user == null){
			throw new BusinessException("用户不存在");
		}

		if (!user.getPassword().equals(registerDto.getPassword())){
			throw new BusinessException("用户名或密码错误");
		}

		// 创建userDto
		UserDto userDto = new UserDto();
		BeanUtil.copyProperties(user,userDto);

		// 将用户dto保存到redis
		redisComponent.saveUserInfoToken(userDto);
		// 将token保存到cookie
		saveTokenToCookie(response,userDto.getToken());

		return getSuccessResponseVO(userDto);
	}

	/**
	 * @description: 修改用户信息
	 * @param userDto 用户修改了的数据，没修改的不用传
	 * @return com.lhd.entity.vo.ResponseVO
	 * @author liuhd
	 * 2025/3/17 14:52
	 */
	@PutMapping("/userInfo")
	public ResponseVO modifyUserInfo(@RequestBody UserDto userDto){

		UserDto userInfo = getUserInfoToken();

		// 手机号校验
		String newPhone = userDto.getPhone();
		if (newPhone != null){
			User user = userService.findUserByPhone(newPhone);
			if (user != null){
				throw new BusinessException("该手机号已经被使用!");
			}
		}

		User user = new User();
		BeanUtil.copyProperties(userDto,user);

		userService.updateUserById(user, userInfo.getId());

		redisComponent.updateUserDto(userDto,userInfo);

		return getSuccessResponseVO(null);
	}

	/**
	 * @description: 修改用户密码
	 * @param passwordDto
	 * @return com.lhd.entity.vo.ResponseVO
	 * @author liuhd
	 * 2025/3/17 16:12
	 */
	@PutMapping("/password")
	public ResponseVO modifyUserPassword(@RequestBody PasswordDto passwordDto){



		String rePassword = passwordDto.getRePassword();
		String newPassword = passwordDto.getNewPassword();
		String email = passwordDto.getEmail();
		String code = passwordDto.getCode();

		String redisCode = redisComponent.getMailCode(email);

		if (!redisCode.equals(code)){
			throw new BusinessException("验证码错误，请重试");
		}

		if (!rePassword.equals(newPassword)){
			throw new BusinessException("两次输入密码不一致!");
		}

		UserQuery userQuery = new UserQuery();
		userQuery.setEmail(email);
		User user = userService.findListByQuery(userQuery).get(0);
		if (user.getPassword().equals(newPassword)){
			throw new BusinessException("新旧密码一致!");
		}

		User userBean = new User();
		userBean.setPassword(newPassword);
		userService.updateByQuery(userBean,userQuery);

		return getSuccessResponseVO(null);
	}

	/**
	 * @description: 向邮箱发送验证码
	 * @param
	 * @return com.lhd.entity.vo.ResponseVO
	 * @author liuhd
	 * 2025/3/24 15:21
	 */
	@PostMapping("/findpwd/sendCode")
	public ResponseVO sendCode(@RequestBody UserDto userDto){
		// 拿到邮箱
		String email = userDto.getEmail();

		if (StrUtil.isBlank(email)){
			throw new BusinessException("邮箱为空,请填写你的邮箱!");
		}

		// 发验证码，并保存到redis
		userService.sendCode(email);


		return getSuccessResponseVO(null);
	}

	@PostMapping("/checkAccount")
	public ResponseVO checkAccount(@RequestBody UserDto userDto){

		String email = userDto.getEmail();
		String username = userDto.getUsername();
		String phone = userDto.getPhone();

		if (StrUtil.isBlank(email)){
			throw new BusinessException("邮箱为空,请填写你的邮箱!");
		}
		if (StrUtil.isBlank(username)){
			throw new BusinessException("用户名为空,请填写你的用户名!");
		}
		if (StrUtil.isBlank(phone)){
			throw new BusinessException("电话为空,请填写你的电话!");
		}

		ArrayList<UserQuery> queryList = new ArrayList<>();
		UserQuery userQuery = new UserQuery();
		UserQuery userQuery1 = new UserQuery();
		UserQuery userQuery2 = new UserQuery();
		userQuery1.setEmail(email);
		userQuery2.setUsername(username);
		userQuery.setPhone(phone);
		queryList.add(userQuery1);
		queryList.add(userQuery);
		queryList.add(userQuery2);

		for (UserQuery query : queryList) {
			List<User> userList = userService.findListByQuery(query);
			if (userList != null && !userList.isEmpty()){
				throw new BusinessException("用户已经存在");
			}
		}

		return getSuccessResponseVO(null);
	}
}